﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Security.Claims;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Authorization;
using Stock.Core.Services;
using Stock.Core;
using Stock.Core.Common;
using Stock.Model;
using Stock.Model.ViewModels;
using System.Collections.Generic;
using Web.Filters;
using Microsoft.IdentityModel.Tokens;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Web.Controllers
{


    /// <summary>
    /// 用户类
    /// </summary>
    public class UserController : BaseApiController
    {
        private readonly IHostingEnvironment _env;
        private readonly IUserService users;

        public UserController(IHostingEnvironment env, IUserService usersSvc)
        {
            _env = env;
            users = usersSvc;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="sy"></param>
        /// <returns></returns>
        [HttpGet()]
        [AllowAnonymous()]
        public async Task<dynamic> Login(LoginData sy)
        {
            string loginname = sy.username;
            string passwords = sy.pwd;
            if (!string.IsNullOrEmpty(loginname) || !string.IsNullOrEmpty(passwords))
            {
                DataEncrypt enpt = new DataEncrypt();
                passwords = enpt.EncryptMD5(passwords);
                var result = await users.Login(loginname, passwords);

                if(result.IsSuccess)
                {
					var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ThisIsASecretKeyForAspNetCoreAPIToken"));
					var options = new TokenProviderOptions
					{
						Audience = "audience",
						Issuer = "issuer",
						SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
					};
					var tpm = new TokenProvider(options);
					var token = await tpm.GenerateToken(HttpContext, sy.username, sy.pwd, "");

					return new BaseResult() { IsSuccess = true, Data = new { userid = result.Data.ToString(), token = token } };
                }
                else
                {
                    return result;
                }

            }
            else
            {
                return new BaseResult() { IsSuccess = false, Message = "请输入用户名、密码", Data = null, DataCount = null };
            }
        }

        [HttpPost()]
        public async Task<dynamic> Insert([FromBody]InsertUser model)
        {
            if(await users.CheckExsit(model.login_name))
            {
                return new BaseResult() { IsSuccess = false, Message="用户名已存在" };
            }
            if(model.parentid != null && model.parentid != "0" && !await users.CheckExsitParent(model.parentid))
            {
                return new BaseResult() { IsSuccess = false, Message = "父帐号不存在" };
            }

            model.pwd = new DataEncrypt().EncryptMD5(model.pwd);

            bool success = await users.Add(model);
            return new BaseResult() { IsSuccess = success };
        }

        [HttpPost()]
		public async Task<IActionResult> Logout()
		{
			await HttpContext.Authentication.SignOutAsync("member");   // Startup.cs中配置的验证方案名

			return RedirectToAction("index", "home");
		}

        [HttpGet()]
        public async Task<dynamic> getCurrentFinance(Guid userid)
		{
            
			return await users.getCurrentFinance(userid);
		}

        [HttpPost()]
        public async Task<dynamic> AddMoneny(Guid userid,double moneny )
        {
            var success = await users.Addmoneny(userid, moneny);

            return new BaseResult() { IsSuccess = success };
        }

		[HttpGet()]
		public async Task<dynamic> GetList()
		{
			var user = await users.GetList();

            return new BaseResult() { IsSuccess = true, Data = user };
		}

		[HttpGet()]
        public async Task<dynamic> GetAddLog(Guid? userid, DateTime? start, DateTime? end)
		{
            var data = await users.AddLog(userid, start, end);

            return new BaseResult() { IsSuccess = true, Data = data };
		}

        [HttpPost()]
        [AllowAnonymous]
        public async Task<dynamic> ChangePwd(string username, string pwd, string newpwd)
        {
            var success = await users.ChangePwd(username, pwd, newpwd);
            return new BaseResult() { IsSuccess = success };
        }

		[HttpGet()]
        [AllowAnonymous]
		public async Task<dynamic> getTime()
		{
            var date = System.DateTime.Now;
            return new BaseResult() { IsSuccess = true, Data = date.ToString("yyyy-MM-dd HH:mm:ss") };
		}

        [HttpGet()]
        public async Task<BaseResult> getBalance(Guid userid)
        {
            var b =await users.getBalance(userid);
            return new BaseResult() { IsSuccess = true, Data = b };
        }
    }
}
